"""
各种正则匹配
"""

import re
from typing import Tuple, Optional
from datetime import datetime


def match_dt_and_level(line: str) -> Optional[Tuple[datetime, str]]:
    """
    匹配一行日志中的时间和日志级别，为了优化，不再匹配 INFO 级别的日志
    :param line: 一行日志
    :return:
    """
    pattern = re.compile(r'\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\.\d{3}\s+(WARN|ERROR)')
    result = re.match(pattern, line)
    if result is None:
        return None
    result = result.group().split()
    dt_str = ' '.join([result[0], result[1]])
    dt = datetime.strptime(dt_str[:dt_str.rfind('.')], '%Y-%m-%d %H:%M:%S')
    level = result[2]
    return dt, level


def is_request_start(line: str) -> bool:
    """
    判断 line 是否为 Request Start 行
    :param line:
    :return:
    """
    pattern = re.compile('=+ \\s+(Request Start)\\s+ =+')
    result = re.match(pattern, line.strip())
    return True if result else False


def is_request_end(line: str) -> bool:
    """
    判断 line 是否为 Request End 行
    :param line:
    :return:
    """
    pattern = re.compile('=+ \\s+(Request End)\\s+ =+')
    result = re.match(pattern, line.strip())
    return True if result else False


def is_response_start(line: str) -> bool:
    """
    判断 line 是否为 Request Start 行
    :param line:
    :return:
    """
    pattern = re.compile('=+ \\s+(Response Start)\\s+ =+')
    result = re.match(pattern, line.strip())
    return True if result else False


def is_response_end(line: str) -> bool:
    """
    判断 line 是否为 Request End 行
    :param line:
    :return:
    """
    pattern = re.compile('=+ \\s+(Response End)\\s+ =+')
    result = re.match(pattern, line.strip())
    return True if result else False


def is_token_error_log(line: str) -> bool:
    """
    判断 line 是否是 token error 的日志
    :param line: 所要解析的日志行
    :return:
    """
    token_error_pattern = re.compile('token解析异常')
    result = re.search(token_error_pattern, line)
    return True if result else False


def is_404_error_log(line: str) -> bool:
    """
    判断 line 是否是 404 错误的日志
    :param line: 所要解析的日志行
    :return:
    """
    _404_error_pattern = re.compile('404没找到请求')
    result = re.search(_404_error_pattern, line)
    return True if result else False


def is_undertow_request_log(line: str) -> bool:
    """
    判断 line 是否是 undertow request 的日志，它是由 Servlet path match failed 导致产生的错误
    :param line:
    :return:
    """
    pattern = re.compile(r'UT005071: Undertow request failed HttpServerExchange')
    result = re.search(pattern, line)
    return True if result else False


def is_dfmc_exception_log(line: str) -> bool:
    """
    判断 line 是否是 DfmcException 的异常
    :param line:
    :return:
    """
    pattern = re.compile(r'o.s.m.dfmc.aspect.DfmcExceptionAdvice')
    result = re.search(pattern, line)
    return True if result else False
